#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import datetime
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains

import utils
from config import CHANNEL_LIST_URL


def check_browser(func):
    def wrapper(self, *args, **kwargs):
        if not self._browser:
            print("Failed to get _browser")
        else:
            return func(self, *args, **kwargs)

    return wrapper


class Code(object):
    def __init__(self):
        self._browser = utils.get_browser()
        print("code browser %x" % id(self._browser))

    @check_browser
    def create(self, codeurl):
        self._browser.get(codeurl)
        time.sleep(3)

        # 点击添加编码流
        add_stream_button = self._browser.find_element_by_class_name(
            'add-stream')
        add_stream_button.click()

        # 填写流名称
        stream_name = self._browser.find_element_by_name('streamName')
        stream_name.send_keys("ls_yy_high")
        time.sleep(3)

        # suggest流名称
        suggest_ul = self._browser.find_element_by_class_name(
            'ui-autocomplete')
        aas = suggest_ul.find_elements_by_tag_name('a')
        is_exit = False
        for a in aas:
            if not is_exit:
                spans = a.find_elements_by_tag_name('span')
                for span in spans:
                    print(span.text)
                    if span.text == 'ls_yy_high':
                        is_exit = True
                        a.click()
                        break

        # 填写RTMP IP
        #stream_IP = self._browser.find_element_by_name('streamIp')
        #stream_IP.send_keys("101.227.14.43")

        # 设置清晰度：流畅
        stream_type_select = Select(
            self._browser.find_element_by_name('streamType'))
        stream_type_select.select_by_index(1)

        # 点击确定按钮
        submit = self._browser.find_element_by_class_name(
            "ui-dialog-buttonset")
        submit.click()

        # 跳转至频道列表页面
        # self._browser.get(CHANNEL_LIST_URL)
